<?php
namespace app\minprogram\controller;


use think\Controller;
use think\Request;
use think\Loader;
use app\common\utils\Redis;
use app\minprogram\model\LoginModel;
use app\api\controller\Utility;
// 小程序授权登录 注册
class Login extends Common
{
    
	//获取微信用户信息 session_key 和 openid
	public function getIndex(Request $request)
	{

		Loader::import('Wxchat.Api');
		// Loader::import('Redis.Redis');

		$code = $request->param('code');

		$wx_min_program_config = load_scope_config('weixin_min_program');
		//var_dump($wx_min_program_config);die;
		$wx_api = new \Api([
			'appId' => $wx_min_program_config['appid'],
			'appSecret' => $wx_min_program_config['app_secret'],
			//'mchId' => $wx_min_program_config['mchid'],
			//'key' => $wx_min_program_config['key']
		]);

		$data = $wx_api->get_min_program_session_by_authorize($code);
		
	// return $data;die;
		if ($data[1] == null) {
			$data = $data[0];
			 to_json_encode(400,'error',$data);
		} else {
			$data = $data[1];
		}

       //TODO:: 获取 用户 基本信息 昵称 头像
        //创建 登录态

		$redis = Redis::instance();
		$session_3rd = $this->session_3rd(); //默认长度是 16位

		$redis->set($session_3rd, $data->session_key . '@@' . $data->openid, 1728000); //20天保质期，微信 session_key 默认30天有效
		//$redis->set($data->openid,$data->session_key . '@@' . $data->openid, 1728000);
		to_json_encode(200, 'success', array('status' => true, 'session_id' =>$session_3rd));

	}
	
    

 // 手机 密码登录
	public function  postLogin(Request $request)
	{
		$session_key_openid = $this->getSessionkeyBysessionId($request->post('session_id'));

		if (empty($session_key_openid)) {
			to_json_encode(400, '无法获取微信Session和Openid', ['status' => false]);

		}
		$expl = explode('@@', $session_key_openid);
		$session_key = $expl[0];
		$openid = $expl[1];
		if (empty($session_key)) {
			to_json_encode(400, '无法获取微信Session', ['status' => false]);

		}

		if (empty($openid)) {
			to_json_encode(400, '无法获取微信Openid', ['status' => false]);

		}
		$phone = $request->post('phone');

		if (!check_valid_phone($phone)) {
			to_json_encode(400, '手机号格式不正确', ['status' => false]);

		}
		$verify_code = $request->post('verify_code');

		$redis = Redis::instance();
		$sess_verify_code = $redis->get(Utility::$sms_template[1].'_'.$phone);

		if ($sess_verify_code != $verify_code) {
			to_json_encode(400, '验证码错误', ['status' => false]);
		}

		$user_name = $request->post('user_name','');
		if($user_name)
		{
			$user_name =filter_emoji($user_name);
		}
		$user_id=LoginModel::saveNewUser($phone, $openid, $user_name);

		if(false === $user_id)
		{
			to_json_encode(400, '该手机号已注册', ['status' => false]);
		}
		to_json_encode(200, 'success', ['status' => true]);

	}
	//手机验证码 登录 未使用
	public function postPhoneLogin(Request $request)
	{
		// Loader::import('Redis.Redis');


	}

}
